package kubevirtsvc

import (
	corev1 "gluenet/internal/agent/api/core/v1"
	"gluenet/internal/agent/driver/virtdriver/options"
)

// vmi不同于kubevirt vmi, 是一个整体资源的声明
func (svc *Service) CreateVirtualMachineInstance(vmi *corev1.KubeVirtVirtualMachineInstance) corev1.CommonResp {
	var err error

	if !svc.objects.IsExist(vmi.GluenetGuid, `vm`) {
		meta := vmi.GluenetMeta
		meta.GluenetKind = `vm`

		vm := corev1.KubeVirtVirtualMachine{GluenetMeta: meta, Spec: vmi.Spec.VirtualMachine}
		if err := svc.createVirtualMachine(&vm); err != nil {
			goto ErrProcess
		}

	}

	if err = svc.vd.StartVMI(vmi.Spec.VirtualMachineInstanceName, options.StartVmiOptions{NameSpace: vmi.GluenetGuid}); err != nil {
		goto ErrProcess
	}

	for _, service := range vmi.Spec.Services {
		meta := vmi.GluenetMeta
		meta.GluenetKind = `vms`
		service.VirtualMachineInstanceName = vmi.Spec.VirtualMachineInstanceName

		kservice := corev1.KubeVirtVirtualMachineService{
			GluenetMeta: meta,
			Spec:        service,
		}

		if err := svc.createVirtualMachineService(&kservice); err != nil {
			goto ErrProcess
		}
	}

	svc.objects.Put(
		vmi.GluenetGuid,
		vmi.GluenetKind,
		&corev1.KubeVirtVirtualMachineInstanceObj{
			GluenetMeta: vmi.GluenetMeta,
			Spec:        vmi.Spec,
			Status:      corev1.Status{State: corev1.StatusReady},
		})

	return corev1.NewCommonSuccessRespWithData(vmi)

ErrProcess:
	svc.logger.Errorf(err.Error())
	return corev1.NewCommonFailureResp(err.Error())
}

func (svc *Service) DeleteVirtualMachineInstance(meta *corev1.GluenetMeta) corev1.CommonResp {
	var err error

	obj, err := svc.objects.Get(meta.GluenetGuid, meta.GluenetKind)
	vmi, ok := obj.(*corev1.KubeVirtVirtualMachineInstanceObj)

	if err != nil && !ok {
		goto ErrProcess
	} else {
		vmi.Status.State = corev1.StatusTerminating
	}

	if err = svc.vd.StopVMI(vmi.Spec.VirtualMachineInstanceName, options.StopVmiOptions{NameSpace: vmi.GluenetGuid}); err != nil {
		goto ErrProcess
	} else {
		vmi.Status.State = corev1.StatusTerminated
	}
	if err = svc.objects.Delete(vmi.GluenetGuid, vmi.GluenetKind); err != nil {
		goto ErrProcess
	}

	return corev1.NewCommonSuccessRespWithData(nil)

ErrProcess:
	vmi.Status.State = corev1.StatusError
	svc.logger.Errorf(err.Error())
	return corev1.NewCommonFailureResp(err.Error())
}
